﻿using DocumentFormat.OpenXml.ExtendedProperties;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using NPOI.HSSF.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.POIFS.Crypt;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Toxy;
using static MsgReader.Outlook.Storage;
using CellType = NPOI.SS.UserModel.CellType;

namespace Growatt.CreateCCode
{
    internal class Program
    {
        static string FileConfigPath = string.Empty;
        public static SystemSafetyParametFileConfig config = null;
        static Dictionary<int, List<string>> dicTempDicListColumnData = new Dictionary<int, List<string>>(); //记载每一列所有数据
        static void Main(string[] args)
        {
            //SampleEXCEl.ShowRowCount("C:\\Users\\Administrator\\Desktop\\DataSample2.xlsx",1,5);
            //SampleEXCEl.ShowRowCount("C:\\Users\\Administrator\\Desktop\\DataSample2.xlsx",2,5);
            //SampleEXCEl.ShowRowGetROWS("C:\\Users\\Administrator\\Desktop\\DataSample2.xlsx");
            //SampleEXCEl.CSVConvertExcel("C:\\Users\\Administrator\\Desktop\\DataResult.CSV", "C:\\Users\\Administrator\\Desktop\\DataResult.xlsx");
            //SampleEXCEl.ShowRowRed("C:\\Users\\Administrator\\Desktop\\DataResult.xlsx", "Sheet1");
            //var dt = SampleEXCEl.ConvertToDataTable("C:\\Users\\Administrator\\Desktop\\DataResult.CSV");
            //SampleEXCEl.ExportToExcel(dt,"C:\\Users\\Administrator\\Desktop\\DataResult.xlsx");
            // SampleEXCEl.ShowRowRedCompareDataMaxMin("C:\\Users\\Administrator\\Desktop\\DataResult.xlsx");





            #region 代码片段
            Debug.WriteLine("当前编码");
            Debug.WriteLine(Encoding.UTF8);

            DicColumnDatas = new Dictionary<string, string>
            {
                { "DATDLEN_NULL", "NULL" },
                { "DATALEN_U8", "Uint8" },
                { "DATALEN_U16", "Uint16" },
                { "DATALEN_U32", "Uint32" },
                { "DATALEN_U64", "FP64U" },
                { "DATALEN_8S", "int8" },
                { "DATALEN_16S", "int16" },
                { "DATALEN_32S", "int32" },
                { "DATALEN_64S", "FP64" }
            };

            pathCurrent = System.IO.Directory.GetCurrentDirectory();
            FileConfigPath = Path.Combine(pathCurrent, "..", "06_TbaleDocument", "FileConfig.xml");
          //  WriteLocalAutoUpdateInfoXml();
            Debug.WriteLine(pathCurrent);
            var autoUpdateConfigXml = FileUtility.ReadFile(Path.Combine(pathCurrent, "..", "06_TbaleDocument", "FileConfig.xml"));//加载Temp下面的配置文件.获取更新的ftp服务器的url
            config = XmlUtility.Deserialize(typeof(SystemSafetyParametFileConfig), autoUpdateConfigXml) as SystemSafetyParametFileConfig;
            if (config != null)
            {
                var mode = config.CreateMode;
                switch (mode)
                {
                    case "0":
                        args = new string[] { pathCurrent };
                        project_1.BuildingCode(args);//生成自定义表格(限制条件)
                        break;
                    case "1":
                        RecordFile(Path.Combine(pathCurrent, "..", "06_TbaleDocument", config.FileModeSafetyMode_2), path2); //生成安规表格
                        break;
                    case "2": //同时生成
                        args = new string[] { pathCurrent };
                        project_1.BuildingCode(args);//生成自定义表格(限制条件)
                        RecordFile(Path.Combine(pathCurrent, "..", "06_TbaleDocument", config.FileModeSafetyMode_2), path2);  //生成安规表格
                        break;
                    case "3":
                        args = new string[] { pathCurrent };
                        project_FirstVersion.BuildingCode(args);//生成自定义表格
                        break;
                    case "4":
                        args = new string[] { pathCurrent };
                        project_FirstVersion.BuildingCode0623(args);//生成自定义表格
                        break;
                }


            }

            #endregion

        }
        static int indexIsOverFlagCount = 1;
        static string path1 = string.Empty;
        static string path2 = string.Empty;
        private static string pathCurrent = string.Empty;
        static List<SafetyParameterModel> ListSafetyParameterModel = new List<SafetyParameterModel>();

        static FileInfoDataModel DefinedDataModel = null;
        static Dictionary<string, string> DicColumnDatas = null;

        static StringBuilder defindeStruct = null;
        static StringBuilder defindeStruct_use = new StringBuilder();
        /// <summary>
        /// 不同路径秀初始化数据
        /// </summary>
        static Dictionary<string, bool> PathDicContent = new Dictionary<string, bool>();

        /// <summary>
        /// 写入本地自动更新配置的XML文件内容
        /// </summary>
        /// <returns></returns>
        public static void WriteLocalAutoUpdateInfoXml()
        {
            string xmlPath = string.Empty, xmlValue = string.Empty;
            xmlPath = FileConfigPath;
            var config = new SystemSafetyParametFileConfig() { FileModeCustom_Mode1 = "Table_Parameter_information_generation_list.xlsx", FileModeSafetyMode_2 = "模板-安规汇总表20231114(保护时间改为20ms量纲+日本安规).xlsx", CodeDirectoryInfo = "05_TableCode", FixedCountSizeof = "250", FileInfoSheetName = "文件信息", SafetyParameterSheetName = "安规参数", CreateMode = "0" };
            xmlValue = XmlUtility.Serializer(typeof(SystemSafetyParametFileConfig), config);
            if (File.Exists(xmlPath))
            {
                File.Delete(xmlPath);
            }
            bool blSuccess = FileUtility.WriteFile(xmlPath, xmlValue);
        }
        /// <summary>
        /// 生成txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 

        static void RecordFile(string _xlsxFilePath, string txtpath)
        {
            try
            {
                string loaclXlsxPath = _xlsxFilePath;
                if (!string.IsNullOrEmpty(loaclXlsxPath))
                {
                    ListSafetyParameterModel.Clear();
                    if (!string.IsNullOrEmpty(loaclXlsxPath))
                    {
                        List<string> stringBuildersList = new List<string>(); //记载每个stringbuild
                        List<string> PathNameList = new List<string>(); //插入文件名称集合
                        var lstdb = ExcelToTable(loaclXlsxPath);
                        var DatatableName = string.Empty;
                        var lis = new List<string>();
                        if (lstdb != null) //获取每个Sheet
                        {
                            lis = lstdb.Select(o => o.TableName).ToList();
                            var index = lis.IndexOf($"{config.SafetyParameterSheetName}");//查找指定表(安规参数)
                            var index2 = lis.IndexOf($"{config.FileInfoSheetName}");//查找指定表 (文件信息)

                            Action ResolveSecSheetData = () =>
                            {
                                if (lstdb != null && lstdb.ElementAtOrDefault(index2) != null)
                                {
                                    var databResolveFileName = lstdb[index2];
                                    List<List<string>> strings = new List<List<string>>();
                                    var dtCol = 0;
                                    for (int i = 0; i < 15; i++)
                                    {
                                        var row = (DataRow)databResolveFileName.Rows[i];
                                        var stringDataChinese = row[dtCol].ToString();
                                        var stringDataValue = row[dtCol + 1].ToString();
                                        if (stringDataValue.Contains("?"))
                                        {
                                            stringDataValue = stringDataValue.Replace("?", "{0}"); //将?转换为数值
                                        }
                                        strings.Add(new List<string>() { stringDataChinese, stringDataValue }); //第一列第二列数值
                                    }
                                    if (strings.Count == 15) //是否有12个配置信息
                                    {
                                        DefinedDataModel = new FileInfoDataModel(strings[0], strings[1], strings[2], strings[3], strings[4], strings[5], strings[6], strings[7], strings[8], strings[9], strings[10], strings[11], strings[12], strings[13], strings[14]);
                                        defindeStruct = new StringBuilder($"#define {DefinedDataModel.cS_SpecNo[1]}              {DefinedDataModel.Count[1]}"); //加宏定义
                                        defindeStruct.AppendLine();
                                        defindeStruct.AppendLine(DefinedDataModel.Length_Eumn[1]); //数据长度宏
                                        defindeStruct.AppendLine(DefinedDataModel.Attribute_Enum[1]);//上下限结构体数组元素个数枚举
                                        defindeStruct.AppendLine(DefinedDataModel.Parameter_Enum[1]); //参数类型枚举
                                        //defindeStruct.AppendLine(DefinedDataModel.Parameter_VoltLevel[1]); //Parameter_VoltLevel
                                        //defindeStruct.AppendLine(DefinedDataModel.Parameter_GetSafetyIndexFromTable[1]); //Parameter_GetSafetyIndexFromTable
                                        defindeStruct.AppendLine($"extern const {DefinedDataModel.SafetySerial[1]} ;"); //M3安规数量
                                        PathNameList.Add(DefinedDataModel.Dev_SafetyPara_h[1]); //获取.h文件
                                        PathNameList.Add(DefinedDataModel.Dev_SafetyPara_c[1]); //获取.c文件
                                    }
                                    else
                                    {
                                        Error("配置信息出错!");
                                    }
                                }
                            };
                            ResolveSecSheetData();        //解析第二个表格
                            if (lstdb != null && lstdb.ElementAtOrDefault(index) != null)
                            {
                                var datab = lstdb[index];
                                Func<DataTable, bool> actio = (n) =>
                                {
                                    bool flag = true;
                                    for (int dtCol = 4; dtCol < n.Columns.Count; dtCol++) //获取每个DataModel
                                    {
                                        for (int i = 4; i < 9; i++) //从第4行开始是否存在空格检查
                                        {
                                            if (i == 7 || i == 8) continue; //第7 8 行不检查 ,长度需检查
                                            var row = (DataRow)n.Rows[i];
                                            if (row[dtCol] == null) flag = false;
                                            if (string.IsNullOrEmpty(row[dtCol].ToString()))
                                            {
                                                Error($"当前从第{i}行{dtCol}位置开始安规表格中存在空字符,请检查!!");
                                                flag = false;
                                            }

                                        }
                                    }
                                    return flag;
                                };
                                var ischeck = actio(datab); if (!ischeck) Error("当前安规表格中存在空字符,请检查!!");
                                DatatableName += datab.TableName + ",";
                                StringBuilder stringBuilderSingleTable = new StringBuilder();
                                StringBuilder stringBuilderTemp = new StringBuilder();
                                ushort CountSizeof = 0; //计数
                                ushort CountSizeofTemp = 0; //临时计算
                                ushort FixedCountSizeof = 250; //固定长度
                                if (ushort.TryParse(config.FixedCountSizeof, out ushort Result))
                                {
                                    FixedCountSizeof = Result;
                                }
                                string defineStructHearder = string.Empty;
                                defineStructHearder = $"#pragma pack({indexIsOverFlagCount})\r\ntypedef struct\r\n{{";

                                StringBuilder listFirstStruct_Define = new StringBuilder(defineStructHearder); //赋值初始值
                                StringBuilder listSecStruct_Define = new StringBuilder(defineStructHearder); //赋值初始值
                                StringBuilder listStructSec_Use = new StringBuilder();

                                for (int dtCol = 3; dtCol < datab.Columns.Count; dtCol++) //获取每个DataModel,从第4行开始
                                {
                                    dicTempDicListColumnData.Add(dtCol, new List<string>());
                                    var list = dicTempDicListColumnData[dtCol];//每一列的所有数据
                                    for (int i = 0; i < datab.Rows.Count; i++)
                                    {
                                        var row = (DataRow)datab.Rows[i];
                                        var fstring = string.Empty;
                                        if (row[dtCol] != null)
                                            fstring = row[dtCol].ToString();
                                        list.Add(fstring);
                                    }
                                }
                                //最后字符串部分赋值;
                                Action endOfStrings = () =>
                                {
                                    var c = FixedCountSizeof - CountSizeof;//(目前还有多少空余)
                                    if (c == 1)
                                    {
                                        for (int kkc = 0; kkc < c; kkc++)
                                        {
                                            listFirstStruct_Define.AppendLine($"Uint8 Reserved{kkc};");
                                            listSecStruct_Define.AppendLine($"Uint8 Reserved{kkc}" + $"[DEFAULTVALUE + {DefinedDataModel.cS_SpecNo[1]}];");
                                        }
                                    }
                                    else if (c > 0) //大于两个
                                    {
                                        var dstring = $"Uint8 Reserved[{c}]";
                                        listFirstStruct_Define.AppendLine(dstring + ";");
                                        listSecStruct_Define.AppendLine(dstring + $"[DEFAULTVALUE + {DefinedDataModel.cS_SpecNo[1]}];");
                                    }
                                    CountSizeof = 0;
                                    CountSizeofTemp = 0;
                                    defineStructHearder = $"#pragma pack({indexIsOverFlagCount})\r\ntypedef struct\r\n{{";

                                    listFirstStruct_Define.AppendLine("} " + string.Format(DefinedDataModel.EE_ST_SAFTYINFO[1], indexIsOverFlagCount) + " ; ");
                                    listSecStruct_Define.AppendLine("} " + string.Format(DefinedDataModel.ST_SAFTY_DEF[1], indexIsOverFlagCount) + " ; ");


                                    //.c
                                    var he1 = $"{string.Format(DefinedDataModel.EE_ST_SAFTYINFO[1], indexIsOverFlagCount)} " + string.Format(DefinedDataModel.stEESaftyInfo[1], indexIsOverFlagCount) + ";";
                                    var he2 = $"const {string.Format(DefinedDataModel.ST_SAFTY_DEF[1], indexIsOverFlagCount)} " + string.Format(DefinedDataModel.stSafty_DefVaule[1], indexIsOverFlagCount) + "= {";

                                    //.h
                                    var he1_extern = $"extern  {string.Format(DefinedDataModel.EE_ST_SAFTYINFO[1], indexIsOverFlagCount)} " + string.Format(DefinedDataModel.stEESaftyInfo[1], indexIsOverFlagCount) + ";"; //info不用加const
                                    var he2_extern = $"extern const {string.Format(DefinedDataModel.ST_SAFTY_DEF[1], indexIsOverFlagCount)} " + string.Format(DefinedDataModel.stSafty_DefVaule[1], indexIsOverFlagCount) + ";";


                                    StringBuilder listHeader_Last_Use_temp = new StringBuilder();

                                    defindeStruct.AppendLine();
                                    listHeader_Last_Use_temp.AppendLine(he1);//第一个个结构体头部赋值;  //需要加声明;
                                    listHeader_Last_Use_temp.AppendLine(he2);//第二个结构体头部赋值
                                    listHeader_Last_Use_temp.AppendLine(listStructSec_Use.ToString()); //第二个结构体内容
                                    listHeader_Last_Use_temp.AppendLine("};");


                                    //总结构体赋值
                                    defindeStruct_use.AppendLine();
                                    defindeStruct_use.AppendLine(listHeader_Last_Use_temp.ToString()); //第二个结构体赋值

                                    //总结构体定义
                                    defindeStruct.AppendLine(listFirstStruct_Define.ToString()); //第一个结构体定义
                                    defindeStruct.AppendLine();
                                    defindeStruct.AppendLine(listSecStruct_Define.ToString()); //第二个结构体定义
                                    defindeStruct.AppendLine(he1_extern); //第一个结构体变量宏定义
                                    defindeStruct.AppendLine(he2_extern); //第二个结构体变量宏定义
                                    defindeStruct.AppendLine();




                                    //Debug.WriteLine(defindeStruct.ToString());
                                    //Debug.WriteLine(defindeStruct_use.ToString());

                                    listFirstStruct_Define.Clear(); // 第一个结构体定义清空
                                    listSecStruct_Define.Clear();


                                    listStructSec_Use.Clear();  //
                                    listFirstStruct_Define.AppendLine(defineStructHearder);
                                    listSecStruct_Define.AppendLine(defineStructHearder);
                                    indexIsOverFlagCount++;
                                };
                                var datas = dicTempDicListColumnData.Keys.ToList();
                                for (global::System.Int32 k = 0; k < datas.Count; k++)
                                {

                                    var KKC = datas[k];//获取键
                                    var values = dicTempDicListColumnData[KKC];
                                    if (string.IsNullOrEmpty(values[0]) || string.IsNullOrEmpty(values[1])) //当读取地址为空时,直接跳过该列
                                        continue; //直接不进行(合并32位数)
                                    if (!string.IsNullOrEmpty(values[3]) && Enum.TryParse(values[3], out CDataType result_DataTypeSample) && !string.IsNullOrEmpty(values[0]) && !string.IsNullOrEmpty(values[1]))
                                    {
                                        SafetyParameterModel dataModel = new SafetyParameterModel()
                                        {
                                            Address = values[0],
                                            NewAddress = values[1],
                                            ParameterName = values[2],
                                            Length = values[3],
                                            Up = values[4],
                                            Load = values[5],
                                            DataTypeSamplEnum = result_DataTypeSample,
                                            DataType = values[6],
                                            ChineseName = values[7],
                                            Uint = values[8],
                                            Index = KKC,
                                            strings = new List<string>(),
                                        };

                                        if (values[3].ToString().Contains("32"))
                                        {
                                            var SaftyListValuesDef = Enumerable.Range(9, values.Count - 9).Select(x =>
                                            {
                                                var f = "0";
                                                //获取两列的数据
                                                if (!string.IsNullOrEmpty(values[x]) && ushort.TryParse(values[x].ToString(), out ushort uresult_32) && !string.IsNullOrEmpty(dicTempDicListColumnData[KKC + 1][x]) && ushort.TryParse((dicTempDicListColumnData[KKC + 1][x]).ToString(), out ushort uresult_32_next))
                                                {
                                                    var temp = result_DataTypeSample.ToString();
                                                    if (DicColumnDatas.ContainsKey(temp))
                                                    {
                                                        if (DicColumnDatas[temp] == "int32")
                                                            f = DuiHelperModbusProtocol.TwoUShortToInt(uresult_32_next, uresult_32).ToString();
                                                        else
                                                            f = DuiHelperModbusProtocol.TwoShortToUInt(uresult_32_next, uresult_32).ToString();
                                                    }

                                                }
                                                return f;
                                            }).ToList();
                                            dataModel.strdataFilnal = $"{{{dataModel.DataTypeSamplEnum},{dataModel.Up},{dataModel.Load},{dataModel.DataType}," + $"{string.Join(",", SaftyListValuesDef)}}}" + ",";
                                            //Debug.WriteLine($"当前参数个数:{KKC}_____" + SaftyListValuesDef.Count);
                                        }
                                        else
                                        {

                                            var SaftyListValuesDef = Enumerable.Range(9, values.Count - 9).Select(x =>
                                            {

                                                var f = "0"; //直接赋值
                                                if (!string.IsNullOrEmpty(values[x]) && ushort.TryParse(values[x].ToString(), out ushort uresult))
                                                    f = uresult.ToString();
                                                return f;

                                            }).ToList();
                                            dataModel.strdataFilnal = $"{{{dataModel.DataTypeSamplEnum},{dataModel.Up},{dataModel.Load},{dataModel.DataType}," + $"{string.Join(",", SaftyListValuesDef)}}}" + ",";
                                            //Debug.WriteLine($"当前参数个数:{KKC}_____" + SaftyListValuesDef.Count);
                                        }
                                        ListSafetyParameterModel.Add(dataModel);
                                        if (dataModel != null)
                                        {
                                            var num = 0;
                                            var strs = Convert.ToString(dataModel.DataTypeSamplEnum);
                                            if (strs.Contains("8")) num = 1;
                                            if (strs.Contains("16")) num = 2;
                                            if (strs.Contains("32")) num = 4;
                                            if (strs.Contains("64")) num = 8;
                                            CountSizeofTemp += (byte)num;
                                            if (CountSizeofTemp <= FixedCountSizeof)
                                            {
                                                CountSizeof = CountSizeofTemp;
                                                try
                                                {
                                                    var typeString = "";
                                                    var tempDataTypeSamplEnumKey = dataModel.DataTypeSamplEnum.ToString();
                                                    if (DicColumnDatas.ContainsKey(tempDataTypeSamplEnumKey))
                                                    {
                                                        typeString = DicColumnDatas[tempDataTypeSamplEnumKey];
                                                        dataModel.DataTypeSamplEnum = result_DataTypeSample;
                                                        var modeString = $"{typeString} {dataModel.ParameterName}";
                                                        listFirstStruct_Define.AppendLine(modeString + ";"); //Uint16 ParamterName_142;
                                                        listSecStruct_Define.AppendLine(modeString + $"[DEFAULTVALUE + {DefinedDataModel.cS_SpecNo[1]}];"); //Uint16 ParamterName_16[DEFAULTVALUE + cS_SpecNo];
                                                        if (CountSizeof != FixedCountSizeof)
                                                        {
                                                            listStructSec_Use.AppendLine(dataModel.strdataFilnal); //例子{DATALEN_U16,LOWERLIMIT,ATTRIBUTE,FREQPARA,8500,8500,8174,8900,8500,8500,8500,8500,8500,8174,8500,8500,8500,8500,8500,8500,9000,9000,8600,6957,8348,8500,8500,8500,7826,8500,9000,9000,9000,9500,8000,5776,9000,8500,8500,8500,8500,8500,8500,8773,9171,9000,8500,8900,8900,8900,8900,8900,8900,8900,8900,9171,8829,8800,8500,8500,8500,8800,8800,8800,8500,8500,8674,8674,8348,9000,9000,8500,9000,9000,8500,8500,9000,8500,8500,9000,8348,8174,9171,9171,8829,9168,9168},
                                                            if (KKC == datab.Columns.Count - 1) //当运行最后一列数时,在最后添加参数
                                                                endOfStrings();

                                                        }

                                                    }
                                                    else
                                                    {
                                                        Error("找不到指定数据类型,生成失败!");
                                                    }
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                            else //1 或者更多的时候
                                            {
                                                endOfStrings();
                                                k--;//遍历回去仍需重头开始
                                            }



                                        }
                                    }
                                    else
                                    {
                                        Error("找不到指定数据类型,生成失败!");
                                    }
                                }
                                //foreach (var Col_item in dicTempDicListColumnData)
                                //{


                                //} 
                            }
                            if (defindeStruct != null)
                            {

                                defindeStruct.AppendLine("#pragma pack()");
                                stringBuildersList.Add(defindeStruct.ToString());
                                defindeStruct_use.AppendLine();

                                var SaftyListValuesDef = Enumerable.Range(9, dicTempDicListColumnData[3].Count - 9).Select(x =>
                                {
                                    var f = "0"; //直接赋值
                                    var uresult = dicTempDicListColumnData[3][x];
                                    if (!string.IsNullOrEmpty(dicTempDicListColumnData[3][x]))
                                        f = uresult.ToString().Replace("0x", "");
                                    f = Convert.ToUInt16(f, 16).ToString();
                                    return f;
                                }).ToList();
                                StringBuilder defindeStruct_temp = new StringBuilder();
                                defindeStruct_temp.AppendLine($"const {DefinedDataModel.SafetySerial[1]}={{");
                                defindeStruct_temp.AppendLine($"{string.Join(",", SaftyListValuesDef)}}};".ToString());

                                defindeStruct_temp.AppendLine(DefinedDataModel.Parameter_VoltLevel[1]); //Parameter_VoltLevel
                                defindeStruct_temp.AppendLine(DefinedDataModel.Parameter_GetSafetyIndexFromTable[1]); //Parameter_GetSafetyIndexFromTable

                                defindeStruct_use.AppendLine(defindeStruct_temp.ToString());



                                stringBuildersList.Add(defindeStruct_use.ToString());
                                WriteFileByFileName(PathNameList, stringBuildersList);
                            }

                        }

                    }
                }

                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Error("生成不成功!,请检查表格");

            }
        }
        private static void Error(string str)
        {
          
            Console.WriteLine(str);
            Console.ReadLine();
        }

        /// <summary>
        /// 根据文件名称记录数据
        /// </summary>
        /// <param name="txtpaths"></param>
        /// <param name="stringBuildersList"></param>
        private static void WriteFileByFileName(List<string> txtpaths, List<string> stringBuildersList)
        {
            try
            {
                //多个Sheet 多个table 多个文件
                if (txtpaths.Count == stringBuildersList.Count)
                {
                    for (int i = 0; i < stringBuildersList.Count; i++)
                    {
                        var name = txtpaths[i];
                        var st = stringBuildersList[i];
                        var val = "".TrimEnd();
                        var dataTable = new System.Data.DataTable();
                        dataTable.Columns.Add(new DataColumn());
                        string listStr = st;
                        DataRow dr1 = dataTable.NewRow();
                        dataTable.Rows.Add(dr1);
                        dr1[0] = listStr;
                        if (dataTable != null && !string.IsNullOrEmpty(name))
                        {
                            string p = "";
                            if (name.Contains(".c"))
                            {
                                p = Path.Combine(pathCurrent, "..", $"{config.CodeDirectoryInfo}", "source", name);
                                RemoveExist(p);
                            }
                            else if (name.Contains(".h"))
                            {
                                p = Path.Combine(pathCurrent, "..", $"{config.CodeDirectoryInfo}", "include", name);
                                RemoveExist(p);
                            }
                            var result = DataToStringTXT2(name, dataTable, val, new List<int>() { dataTable.Columns.Count - 1 }, "Custom" + "_");

                        }
                    }
                    Debug.WriteLine("生成成功!");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("生成失败!");
            }




        }
        static string fixData = "/************************Fixed Excel spanned data end **********************/";

        static void RemoveExist(string path)
        {
            if (!File.Exists(path))
                using (StreamWriter streamWriter = new StreamWriter(path, false)) { }//直接创建
            if (!PathDicContent.ContainsKey(path))
            {
                PathDicContent.Add(path, true);
                var strings = LoadFilelistString(path).ToList();
                var ind1 = 0;
                var ind2 = 0;
                var fin = false;
                for (int i = 0; i < strings.Count; i++)
                {
                    var itemstring = strings[i];

                    if (!fin && itemstring.Equals("/************************Excel spanned data start**********************/"))
                    {
                        ind1 = i;
                        fin = true;
                    }
                    if (itemstring.Equals("/************************Excel spanned data end**********************/"))
                    {
                        ind2 = i;
                    }

                }

                if (ind1 != 0 && ind2 != 0 && ind2 > ind1)
                {
                    var count = ind2 - ind1;
                    if (count > 0)
                    {
                        strings.RemoveRange(ind1, count + 1); //删除多余的行
                    }
                }
                if (!strings.Contains(fixData))
                    strings.Add(fixData);
                if (!keyValuePairs.ContainsKey(path)) //第一次需要添加原先内容
                {
                    keyValuePairs.Add(path, strings);

                }
            }

        }

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }
        public static int getAllRow(ISheet sheet)
        {
            // 遍历所有行

            int rows = -1;
            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null && row.Cells.Count > 0 && row.Cells[0] != null && !string.IsNullOrEmpty(row.Cells[0].ToString())) // 检查行是否为空
                {
                    rows++;
                }
            }
            return rows;
        }
        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static List<System.Data.DataTable> ExcelToTable(string file)
        {

            List<System.Data.DataTable> dataTables = new List<System.Data.DataTable>();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fileStream = File.OpenRead(file))
            {
                //using (dynamic fs = new  POIFSFileSystem(fileStream))
                //{
                //    //加密文件对象
                //    EncryptionInfo info = new EncryptionInfo(fs);
                //    Decryptor decryptor = Decryptor.GetInstance(info);
                //    //设置开启密码
                //    bool isPasswordCorrect = decryptor.VerifyPassword("123");
                //    var stream = decryptor.GetDataStream(fs);
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fileStream); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fileStream); } else { workbook = null; }
                if (workbook == null) { return null; }
                int count = workbook.NumberOfSheets; //获取所有SheetName

                for (int CC = 0; CC < count; CC++)
                {
                    ISheet sheet = workbook.GetSheetAt(CC);
                    DataTable dt = new DataTable();
                    dt.TableName = sheet.SheetName;
                    dataTables.Add(dt);
                    //表头  
                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    List<int> columns = new List<int>();
                    for (int i = 0; i < SampleEXCEl.GetCellCount(header); i++)
                    {
                        object obj = GetValueType(header.GetCell(i));
                        if (obj == null || obj.ToString() == string.Empty)
                        {
                            dt.Columns.Add(new DataColumn("Columns" + $"{Guid.NewGuid()}" + i.ToString()));
                        }
                        else
                            dt.Columns.Add(new DataColumn(obj + $"{Guid.NewGuid()}".ToString()));
                        columns.Add(i);
                    }
                    //数据  
                    for (int i = sheet.FirstRowNum + 1; i <= getAllRow(sheet); i++)
                    {
                        DataRow dr = dt.NewRow();
                        bool hasValue = false;
                        foreach (int j in columns)
                        {
                            dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                            if (dr[j] != null && dr[j].ToString().Contains("Formula"))
                            {
                                sheet.GetRow(i).GetCell(j).SetCellType(CellType.String);
                                dr[j] = sheet.GetRow(i).GetCell(j).StringCellValue;
                                //ICell cell = sheet.GetRow(i).GetCell(j);
                                ////自定义公式
                                //string Formula = cell.CellFormula;
                                ////给列设置公式
                                //cell.SetCellFormula(Formula);
                                ////这个很重要，在Execl创建公式
                                //workbook.GetCreationHelper().CreateFormulaEvaluator().EvaluateFormulaCell(cell);
                                ////获取其值
                                //GetValueType(sheet.GetRow(i).GetCell(j));
                            }

                            if (dr[j] != null && dr[j].ToString() != string.Empty)
                            {
                                hasValue = true;
                            }
                        }
                        if (hasValue)
                        {
                            dt.Rows.Add(dr);
                        }
                    }


                }

            }
            return dataTables;
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                    return "Formula";
                default:
                    return "=" + cell.CellFormula;
            }
        }
        public static List<System.Data.DataTable> ReadFromExcelToDatatype(string FilePath, List<int> listSheet = null)
        {
            List<System.Data.DataTable> dataTables = new List<System.Data.DataTable>();
            try
            {
                // 解析xlsx文档
                ParserContext context = new ParserContext(FilePath);
                ISpreadsheetParser parser = ParserFactory.CreateSpreadsheet(context);
                ToxySpreadsheet ss = parser.Parse();
                if (ss.Tables.Count > 0)
                {
                    listSheet = Enumerable.Range(0, ss.Tables.Count).ToList();
                    for (int s = 0; s < ss.Tables.Count; s++)
                    {
                        if (listSheet != null && listSheet.Contains(s))
                        {
                            var dtToxyTable = ss.Tables[s];
                            var titlename = dtToxyTable.Rows[0].Cells.Where(o => !string.IsNullOrWhiteSpace(o.Value.ToString())).Select(o => o.Value.ToString()).Distinct().ToList();//不允许出现重名且空白的列
                            var listString = string.Join(",", titlename);
                            //Debug.WriteLine(listString);
                            var dtPart = dtToxyTable.ToDataTable();

                            var OriginalCountCol = dtPart.Columns.Count;
                            for (int i = 0; i < OriginalCountCol; i++)
                            {
                                if (i <= titlename.Count - 1)
                                    dtPart.Columns[i].ColumnName = titlename[i].ToString();
                                else
                                    dtPart.Columns.RemoveAt(dtPart.Columns.Count - 1);
                            }
                            if (dtPart.Rows.Count > 0)
                                dtPart.Rows.RemoveAt(0);
                            dataTables.Add(dtPart);
                        }
                        else if (listSheet == null)  //默认全部读取sheet
                        {
                            var dtAll = ss.Tables[s].ToDataTable();

                            dataTables.Add(dtAll);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                Debug.WriteLine("生成不成功!");
                Environment.Exit(0);
            }
            return dataTables;
        }

        static Dictionary<string, List<string>> keyValuePairs = new Dictionary<string, List<string>>();
        #region Data
        //public static bool DataToStringTXT(string txtpath, DataTable table, string strHeader, List<int> lstVisibleColumn = null, string fileName = "", bool ShowHeader = false)
        //{
        //    bool result = false;
        //    try
        //    {
        //        string delimiter = ",";
        //        string path = "";
        //        if (txtpath.Contains(".c"))
        //        {
        //            path = Path.Combine(pathCurrent, "..", $"{config.CodeDirectoryInfo}", "source", txtpath);
        //        }
        //        else if (txtpath.Contains(".h"))
        //        {
        //            path = Path.Combine(pathCurrent, "..", $"{config.CodeDirectoryInfo}", "include", txtpath);
        //        }
        //        var strings = new List<string>();
        //        if (File.Exists(path))
        //        {
        //            bool isappended = true;
        //            if (!keyValuePairs.ContainsKey(path))
        //            {
        //                isappended = false;

        //                bool fin = false;
        //                strings = LoadFilelistString(path).ToList();
        //                var ind1 = 0;
        //                var ind2 = 0;
        //                for (int i = 0; i < strings.Count; i++)
        //                {
        //                    var itemstring = strings[i];

        //                    if (!fin && itemstring.Contains("Excel spanned data start"))
        //                    {
        //                        ind1 = i;
        //                        fin = true;
        //                    }
        //                    if (itemstring.Contains("Excel spanned data end"))
        //                    {
        //                        ind2 = i;
        //                    }

        //                }
        //                if (ind1 != 0 && ind2 != 0 && ind2 > ind1)
        //                {
        //                    var count = ind2 - ind1;
        //                    if (count > 0)
        //                    {
        //                        strings.RemoveRange(ind1, count + 1); //删除多余的行
        //                        ind1 = 0;
        //                        ind2 = 0;
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                isappended = true;
        //            }
        //            StringBuilder stringBuilder = new StringBuilder();
        //            StreamWriter sw = new StreamWriter(path, isappended);
        //            try
        //            {
        //                if (ShowHeader)
        //                    stringBuilder.AppendLine(strHeader);
        //                stringBuilder.AppendLine();
        //                stringBuilder.AppendLine("/************************Excel spanned data start**********************/");
        //                stringBuilder.AppendLine("/*生成代码*/");
        //                for (int i = 0; i < table.Rows.Count; i++)
        //                {
        //                    string strBufferLine = "";
        //                    for (int j = 0; j < table.Columns.Count; j++)
        //                    {
        //                        if (lstVisibleColumn != null && lstVisibleColumn.FindAll(o => o.ToString() == j.ToString()) != null)
        //                        {
        //                            strBufferLine += table.Rows[i][j].ToString() + delimiter;
        //                        }
        //                        else if (lstVisibleColumn == null)
        //                            strBufferLine += table.Rows[i][j].ToString() + delimiter;

        //                        if (j == table.Columns.Count - 1 && table.Columns.Count > 0)
        //                            strBufferLine = DelLastComma(strBufferLine);
        //                    }
        //                    stringBuilder.AppendLine(strBufferLine);
        //                }
        //                stringBuilder.AppendLine();
        //                stringBuilder.AppendLine();
        //                stringBuilder.AppendLine();
        //                stringBuilder.AppendLine();
        //                stringBuilder.AppendLine();
        //                stringBuilder.AppendLine("/************************Excel spanned data end**********************/");
        //                if (!keyValuePairs.ContainsKey(path)) //第一次需要添加原先内容
        //                {
        //                    keyValuePairs.Add(path, strings);
        //                    if (strings.Count > 0)
        //                    {
        //                        for (global::System.Int32 i = 0; i < strings.Count(); i++)
        //                        {
        //                            var item = strings[i];
        //                            sw.WriteLine(item.ToString());
        //                        }
        //                    }
        //                }
        //                sw.WriteLine(stringBuilder.ToString());//插入指定内容
        //                sw.Close();
        //            }
        //            catch (Exception e)
        //            {
        //                Debug.WriteLine(e.ToString());
        //            }
        //            finally
        //            {
        //                result = true;
        //                sw.Close();
        //            }
        //        }
        //        else { Debug.WriteLine(".c/.h文件不存在"); }
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.WriteLine(".c/.h文件不存在");
        //        Debug.WriteLine(ex.Message);
        //    }

        //    return result;
        //} 
        #endregion
        public static bool DataToStringTXT2(string txtpath, DataTable table, string strHeader, List<int> lstVisibleColumn = null, string fileName = "", bool ShowHeader = false)
        {
            bool result = false;
            try
            {
                string delimiter = ",";
                string path = "";
                if (txtpath.Contains(".c"))
                {
                    path = Path.Combine(pathCurrent, "..", $"{config.CodeDirectoryInfo}", "source", txtpath);
                }
                else if (txtpath.Contains(".h"))
                {
                    path = Path.Combine(pathCurrent, "..", $"{config.CodeDirectoryInfo}", "include", txtpath);
                }
                var strings = new List<string>();
                if (File.Exists(path))
                {

                    StringBuilder stringBuilder = new StringBuilder();
                    StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"));
                    try
                    {
                        if (ShowHeader)
                            stringBuilder.AppendLine(strHeader);
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine("/************************Excel spanned data start**********************/");
                        stringBuilder.AppendLine("/*生成代码*/");
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            string strBufferLine = "";
                            for (int j = 0; j < table.Columns.Count; j++)
                            {
                                if (lstVisibleColumn != null && lstVisibleColumn.FindAll(o => o.ToString() == j.ToString()) != null)
                                {
                                    strBufferLine += table.Rows[i][j].ToString() + delimiter;
                                }
                                else if (lstVisibleColumn == null)
                                    strBufferLine += table.Rows[i][j].ToString() + delimiter;

                                if (j == table.Columns.Count - 1 && table.Columns.Count > 0)
                                    strBufferLine = DelLastComma(strBufferLine);
                            }
                            stringBuilder.AppendLine(strBufferLine);
                        }
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine("/************************Excel spanned data end**********************/");
                        if (keyValuePairs[path].Count > 0)
                        {
                            var list = keyValuePairs[path];
                            bool fl = false;
                            for (global::System.Int32 i = 0; i < list.Count(); i++)
                            {
                                var item = list[i];
                                sw.WriteLine(item.ToString());
                                if (item.Equals(fixData) && !fl)
                                {
                                    sw.WriteLine(stringBuilder.ToString());//插入指定内容
                                    fl = true;
                                }
                            }
                        }
                        sw.Close();
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.ToString());
                    }
                    finally
                    {
                        result = true;
                        sw.Close();
                    }

                }
                else { Debug.WriteLine(".c/.h文件不存在"); }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(".c/.h文件不存在");
                Debug.WriteLine(ex.Message);
            }

            return result;
        }
        public static IEnumerable<string> LoadFilelistString(string FileToRead)
        {
            IEnumerable<string> line = null;
            // Creating enumerable object
            if (File.Exists(FileToRead))
                line = File.ReadLines(FileToRead);
            return line;
        }

    }
}
